from flask import Flask,Blueprint,make_response,jsonify,request
from Flask_run import db
from database.lib.message import Message,req_json
from database.lib.mail import SendVerifyCodeEmail
from database.lib.randomcode import RandomSalt,VerifyCode
from database.lib.encryption import encryption,disencryption
from database.models.user import User
from database.tools.configs import defult_hosptital,verify_code_use_once
import datetime
import json

numcount = 1
model_login_page = Blueprint('model_login_page',__name__)


@model_login_page.route('/test1',methods = ["GET", "POST"])
def dsf():
  data = request.get_data()
  data = json.loads(data)
  study_id = data['study_id'] 
  print(study_id)
  return jsonify(status="success")


@model_login_page.route('/loginbypassword',methods = ["POST"])
def loginbypassword():
    data = request.get_json()
    print(data)
    account = data['username']
    password = data['password']
    result = db.session.query(User.account, User.access, User.password, User.name).filter(User.account == account).first()
    if result is None:
        #用户不存在,状态码待定
        content = {"code": 60204, "message": '用户名不存在'}
        return jsonify(content)
    else:
        password = str(encryption(password))
        if password == result.password:
            if result.access == 1:
                token = 'admin-token'
            else:
                token = 'user-token'
            content = {"code": 20000, "data": token}
            return jsonify(content)
        else:
            content = {"code": 60204, "message": '用户名或密码错误'}
            return jsonify(content)

@model_login_page.route('/loginout',methods = ["POST"])
def loginout():
    content = {"code": 20000, "data":'success'}
    return jsonify(content)


@model_login_page.route('/logingetinfo',methods = ["GET"])
def logingetinfo():
    token=request.args.get("token")
    print(token)
    users = {
    'admin-token': {
        'roles': ['admin'],
        'name': 'Super Admin'
    },
    'user-token': {
        'roles': ['user'],
        'name': 'Normal Editor'
    }}
    info = users[token]
    print(info)
    if (info):
        content = {"code": 20000, "data":info}
        return content
    else:
        content = {'code': 50008, 'message': '登录失败。不能获得用户信息'}
        return content

        
@model_login_page.route('/loginbyverifycode',methods = ["POST"])
def loginbyverifycode():
    data = req_json()
    account = data['account']
    verifycode = data['verifycode']
    result = User.query.filter(User.account == account).first()
    if result is None:
        #用户不存在,状态码待定
        msg = Message(201,{},"用户名或验证码错误")
        return msg.response()
    else:
        if datetime.datetime.now() >= result.verifydate+datetime.timedelta(minutes=30):
            msg = Message(201,{},"验证码已经过期请重新获取")
            return msg.response()
        if verifycode == result.verifycode:
            content = {}
            content['name'] = result.name
            content['access'] = result.access
            # and 其他需要的信息
            try:
                #验证码使用成功后自动过期
                if verify_code_use_once:
                    User.query.filter(User.account == account).update({'verifydate':datetime.datetime.now()-datetime.timedelta(minutes=31)})
                    db.session.commit()
            except:
                #验证码过期过程的失败处理，不一定需要
                pass

            msg = Message(data=content)
            return msg.response()
        else:
            msg = Message(201,{},"用户名或验证码错误")
            return msg.response()
 

@model_login_page.route('/getverifycodebymail',methods = ["POST"])
def getverifycodebymail():
    data = req_json()
    account = data['account']
    result = User.query.filter(User.account == account).first()
    if result is None:
        msg = Message(201,{},"用户不存在")
        return msg.response()
    else:
        verifycode = VerifyCode()
        nowtime = datetime.datetime.now()
        try:
            User.query.filter(User.account == account).update({'verifycode':verifycode,'verifydate':nowtime})
            db.session.commit()
        except:
            msg = Message(501,{},"数据库写入异常")
            return msg.response()
        try:
            SendVerifyCodeEmail(str(result.email),verifycode)
        except:
            msg = Message(501,{},"邮件发送异常可能是邮箱地址不允许")
            return msg.response()
    msg = Message(200,{})
    return msg.response()

@model_login_page.route('/regeistedbyadmin',methods = ["POST"])
def regeistedbyadmin():
    data = request.get_json()
    account = data['name']
    password = data['password']
    access = data['access']
    if data  == '' or password == '' or access == '':
        content = {'code': 201, "message": "信息不能为空"}
        return content
    if len(password) < 6:
        content = {'code': 201, "message": "密码长度不小于6位"}
        return content
    result = User.query.filter(User.account == account).first()
    if result is None: # 用户不存在
        if access == "高级用户":
            access = 1
        else:
            access = 0
        newuser = User(account=account,password=str(encryption(password)),access=access,name='', email='', phone='', hosptital='',creator='')
        try:
            db.session.add(newuser)
            db.session.commit()
        except:
            content = {'code': 201, "message": "数据写入异常"}
            return content
        content = {'code': 20000, "message": "注册成功"}
        return content
    else:
        content = {'code': 201, "message": "用户名已存在"}
        return content




@model_login_page.route('/resetpasswordbyverifycode',methods = ["POST"])
def resetpasswordbyverifycode():
    data = req_json()
    account = data['account']
    verifycode = data['verifycode']
    newpassword = data['newpassword']
    result = User.query.filter(User.account == account).first()
    if result is None:
        #用户不存在,状态码待定
        msg = Message(201,{},"用户名或验证码错误")
        return msg.response()
    else:
        if datetime.datetime.now() >= result.verifydate+datetime.timedelta(minutes=30):
            msg = Message(201,{},"验证码已经过期请重新获取")
            return msg.response()
        if verifycode == result.verifycode:
            try:
                User.query.filter(User.account == account).update({'password':str(encryption(newpassword))})
                db.session.commit()
            except:
                msg = Message(501,{},"数据库写入异常")
                return msg.response()
            else:
                try:
                #验证码使用成功后自动过期
                    if verify_code_use_once:
                        User.query.filter(User.account == account).update({'verifydate':datetime.datetime.now()-datetime.timedelta(minutes=31)})
                        db.session.commit()
                except:
                    #验证码过期过程的失败处理，不一定需要
                    pass
                msg = Message(200,{},"修改成功")
                return msg.response()
        else:
            msg = Message(201,{},"用户名或验证码错误")
            return msg.response()
#if account is exis 可用于注册的时候判断等
@model_login_page.route('/ifaccountisexis',methods = ["POST"])
def ifaccountisexis():
    data = req_json()
    account = data['account']
    result = User.query.filter(User.account == account).first()
    if result is None:
        #用户不存在,状态码待定
        msg = Message(200,{},"账户已经存在")
        return msg.response()
    else:
        
        msg = Message(200,{},"账户不存在")
        return msg.response()
       